package main

import (
	"fmt"
	"os"
	"time"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

func main() {

	sugar := zap.NewExample().Sugar()
	defer sugar.Sync()

	sugar.Infow("响应信息", "姓名", "张三", "年龄", "24")
	sugar.Errorf("错误信息: %v", "请求出错")

	logger1 := zap.NewExample()
	defer logger1.Sync()
	logger1.Info("响应信息", zap.String("姓名", "李四"), zap.Int("年龄", 43))
	logger1.Error("错误信息", zap.String("编码", "401"))

	err := os.MkdirAll("logs", 0755)
	if err != nil {
		panic(fmt.Sprintf("文件创建失败: %v", err))
	}
	config := zap.Config{
		Level:            zap.NewAtomicLevelAt(zap.InfoLevel),
		Development:      true,
		Encoding:         "console",
		OutputPaths:      []string{"stdout", "logs/app.log"},
		ErrorOutputPaths: []string{"stderr"},
		EncoderConfig: zapcore.EncoderConfig{
			TimeKey:    "time",
			LevelKey:   "level",
			NameKey:    "logger",
			CallerKey:  "caller",
			MessageKey: "msg",
			// StacktraceKey: "stacktrace",
			LineEnding:  zapcore.DefaultLineEnding,
			EncodeLevel: zapcore.CapitalColorLevelEncoder,
			// EncodeTime:  zapcore.ISO8601TimeEncoder,
			EncodeTime: zapcore.TimeEncoder(func(t time.Time, pae zapcore.PrimitiveArrayEncoder) {
				pae.AppendString(t.Format("2006-01-02 15:04:05"))
			}),
			EncodeDuration: zapcore.StringDurationEncoder,
			EncodeCaller:   zapcore.ShortCallerEncoder,
		},
	}

	logger2, err := config.Build()
	if err != nil {
		panic(fmt.Sprintf("创建失败: %v", err))
	}
	defer logger2.Sync()
	logger2.Info("响应信息", zap.String("爱好", "足球"))
	logger2.Warn("警告信息")
	logger2.Error("错误信息")
}
